package com.ludomancy.starwave;

import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class LevelManager extends DefaultHandler
{
	public static Vector levels = new Vector();
	
	private Level currentMission;
	private String levelData;
	private String description;

	public static void loadMissions()
	{
		try
		{
			InputStream is = StarWaveApplet.app.getClass().getResourceAsStream("/levels.xml");
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(is, new LevelManager());
			is.close();
		}
		catch(Exception e)
		{
			
		}
	}

	public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException
	{
		if(qName.equals("level"))
		{
			levelData = new String();
			description = attr.getValue("desc");
			if(description != null)
			{
				if(description.equals(""))
				{
					description = null;
				}
				else
				{
					description = description.replaceAll("\\\\n", "\n");
				}
			}
		}
		else
		{
			levelData = null;
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException
	{
		if(levelData != null)
		{
			String entry = new String(ch, start, length);
			entry = entry.replaceAll(" ", "");
			entry = entry.replaceAll("\n", "");
			entry = entry.replaceAll("\r", "");
			entry = entry.trim();
			levelData += entry;
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		if(levelData != null)
		{
			// parse data
			String[][] map = new String[Game.GRID_HEIGHT][Game.GRID_WIDTH];
			levelData +=".NON"; // hack
			String [] ships = levelData.split("\\.");
			int row = 0;
			for (int i = 0; i < Game.GRID_HEIGHT*Game.GRID_WIDTH; i += Game.GRID_WIDTH)
			{
				System.arraycopy(ships, i, map[row], 0, Game.GRID_WIDTH);
				row++;
			}
			
			currentMission = new Level(map, description);
			levels.add(currentMission);
			levelData = null;
		}
	}

	public static boolean isLastLevel(int level)
	{
		if(Game.EDITOR)
		{
			return false;
		}
		return level == getLevelCount();
	}

	public static int getLevelCount()
	{
		return levels.size();
	}
}
